package com.own.business.log.login.persistence.business.hook;

import com.own.business.log.login.persistence.business.service.LogLoginElasticService;
import com.own.business.log.login.persistence.entity.po.LogLoginElasticPo;
import com.own.component.log.login.core.PersistenceLogLoginHook;
import com.own.component.log.login.entity.LogLoginEntity;
import com.own.component.util.time.ZonedDateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * DefaultAfterLogLoginHook
 *
 * @author chenxueli
 * @date 2023-12-20 10:28:56
 */
@Slf4j
@Component("persistenceLogLoginHook")
public class DefaultAfterLogLoginHook implements PersistenceLogLoginHook {

    @Resource
    private LogLoginElasticService logLoginElasticService;

    /**
     * 执行方法
     *
     * @param entity 日志信息
     */
    @Override
    public void run(LogLoginEntity entity) {
        var po = new LogLoginElasticPo();
        var loginUser = entity.getLoginUser();
        if (loginUser != null) {
            po.setFkUserId(loginUser.userId());
            po.setUserName(loginUser.userName());
            po.setToken(loginUser.token());
        }
        po.setId(UUID.randomUUID().toString());
        po.setGmtCreate(ZonedDateTimeUtil.of(entity.getLoginTime()));
        po.setIp(entity.getIp());
        po.setClient(entity.getClient());
        po.setStatus(entity.getStatus().getType());
        po.setLoginAccount(entity.getLoginAccount());
        po.setLoginType(entity.getLoginType());
        po.setLoginCode(entity.getLoginCode());
        po.setExtra(entity.getExtra());
        po.setTraceId(entity.getTraceId());
        po.setHeaderParams(entity.getHeaders());
        logLoginElasticService.add(po);
    }

}
